class TodoApp{
    constructor(){
        this.todos=[] //将从localStorage加载

        this.initApp()  //初始化UI和事件处理
    }

    async initApp(){
               try {
            // 显示加载指示器
            this.showLoadingIndicator();
            
            // 从API获取任务数据
            this.todos = await TodoAPI.getAllTodos();
            
            // 获取DOM元素
            const todoListContainer = document.getElementById('todo-list');
            const emptyListElement = document.getElementById('empty-list');
            
            // 初始化UI渲染器
            this.todoUI = new TodoUI(todoListContainer, emptyListElement);
            
            // 初始化事件处理器
            this.todoEvents = new TodoEvents(this.todoUI, this.todos);
            
            // 渲染初始任务列表
            this.todoUI.renderTodoList(this.todos);
            
            // 隐藏加载指示器
            this.hideLoadingIndicator();
            
            console.log('Todo应用初始化成功');
        } catch (error) {
            console.error('Todo应用初始化失败:', error);
            this.showErrorMessage('加载任务失败，请刷新页面重试');
        }
    }


    // 显示加载指示器

 showLoadingIndicator() {
        const loadingEl = document.createElement('div');
        loadingEl.id = 'loading-indicator';
        loadingEl.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center bg-white bg-opacity-75';
        loadingEl.style.zIndex = '1000';
        loadingEl.innerHTML = `
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">加载中...</p>
            </div>
        `;
        document.body.appendChild(loadingEl);
    }

    /**
     * 隐藏加载指示器
     */


      hideLoadingIndicator() {
        const loadingEl = document.getElementById('loading-indicator');
        if (loadingEl) {
            loadingEl.remove();
        }
    }

      
    /**
     * 显示错误消息
     * @param {string} message - 错误消息
     */


     showErrorMessage(message) {
        this.hideLoadingIndicator();
        
        const errorEl = document.createElement('div');
        errorEl.className = 'alert alert-danger position-fixed top-0 start-0 m-3';
        errorEl.style.zIndex = '1001';
        errorEl.innerHTML = `
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            ${message}
            <button type="button" class="btn-close float-end" onclick="this.parentElement.remove()"></button>
        `;
        document.body.appendChild(errorEl);
        
        // 5秒后自动移除
        setTimeout(() => {
            if (document.body.contains(errorEl)) {
                errorEl.remove();
            }
        }, 5000);
    }
}

// 当DOM加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 创建并启动应用
    window.todoApp = new TodoApp();
}); 